package com.example.casserver.security;

import com.example.casserver.util.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 * 用于处理基于JWT的API认证
 * 继承OncePerRequestFilter确保每个请求只执行一次过滤
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserDetailsService userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.userDetailsService = userDetailsService;
    }

    /**
     * 执行过滤器逻辑
     * 1. 从请求头中提取JWT令牌
     * 2. 验证令牌并获取用户信息
     * 3. 设置Spring Security上下文
     *
     * @param request  HTTP请求
     * @param response HTTP响应
     * @param chain    过滤器链
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        // 从Authorization头中提取JWT令牌
        final String authHeader = request.getHeader("Authorization");
        String username = null;
        String jwt = null;

        // 检查Authorization头是否存在且格式正确
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            jwt = authHeader.substring(7);
            username = jwtUtil.validateTokenAndGetUsername(jwt);
        }

        // 如果找到有效的JWT令牌且用户未认证
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 加载用户详情
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            // 创建认证令牌
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            // 设置安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        // 继续过滤器链
        chain.doFilter(request, response);
    }
} 